﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using MongoDB.Driver.Linq;
using MongoDB.Bson;
using MongoDB.Driver.Builders;

namespace DatabaseRepository
{
    public class NewsRepository : INewsRepository
    {
        private readonly MongoConnectionHelper<News> _news;

        public NewsRepository() {
            _news = new MongoConnectionHelper<News>();
        }

        public bool AddNews(string headline, string text) { 
            try
            {
                _news.Collection.Save(new News {Headline = headline, Message = text, Date = DateTime.Now, LastEdited = default(DateTime)});
                return true;
            }
            catch (Exception) {
                return false;
            }
        }

        public bool EditNews(string id, string headline, string message)
        {
            try
            {                
                _news.Collection.Update(Query.EQ("_id", new ObjectId(id)), Update.Set("Headline", headline).Set("Message", message).Set("LastEdited", DateTime.Now));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool DeleteNews(string id) {
            try
            {
                _news.Collection.Remove(Query.EQ("_id", new ObjectId(id)));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public IEnumerable<News> GetNewsPosts() {
            try {
                return (from n in _news.Collection.AsQueryable()
                        orderby n.Date descending
                        select n).ToList();
            }
            catch (Exception)
            {
                return new List<News>();
            }
        }
    }
}
